<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button data-path="news">新闻</button>
    <button data-path="play">娱乐</button>
    <button data-path="music">音乐</button>
    <div id="view"></div>
    <script>
      // 路由表单
      const routes = [
        { path: 'news', content: '我是新闻组件' },
        { path: 'play', content: '我是娱乐组件' },
        { path: 'music', content: '我是音乐组件' },
      ];

      // 获取元素
      let btns = document.querySelectorAll('button');
      let view = document.querySelector('#view');

      //步骤：事件改变地址栏-->监听地址栏改变-->视图变化

      // 1点击按钮改变地址栏
      btns.forEach((item) => {
        item.onclick = function () {
          // 通过自定义属性让每个按钮带上地址-->获取按钮的自定义属性-->将获取到的值赋值给地址栏
          console.log(this.dataset.path);
          location.hash = this.dataset.path;
        };
      });
      // 2监听地址栏变化
      window.onhashchange = function (e) {
        // console.log(e);
        const newPath = e.newURL.split('#')[1];
        // console.log(newPath);
        // 3对照路由表改变视图
        routes.forEach((item) => {
          // console.log(item.path);
          if (newPath === item.path) {
            view.textContent = item.content;
          }
        });
      };
    </script>
  </body>
</html>
